class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
    /*  int cnt=1;
      ListNode* h=head,*l=head,*t=NULL;
      while(cnt<left){
        if(cnt==left-1){
          t=h;
        }
        h=h->next;
        cnt++;
      }
      l=h;
      while(cnt<right){
        l=l->next;
        cnt++;
      }
      ListNode* r = l->next,*p=head;
      if(h->next==NULL||h==NULL) return head;
      while(h!=l->next&&h!=NULL){
        p=h->next;
        h->next=r;
        r=h;
        h=p;
      }
      if(t!=NULL){
        t->next=r;
      }
      return head;*/
      ListNode* t=NULL,*h=head,*p=NULL,*r=NULL;
      int cnt=1;
      while(cnt<right){
        if(cnt==left-1){
          t=h;
        }
        if(cnt<left){
          h=h->next;
        }else if(cnt==left){
          r=h;
        }
        if(cnt>=left&&cnt<right){
          p=r->next;
          r->next=p->next;
          p->next=h;
          if(t!=NULL){
            t->next=p;
          }else{
            head=p;
          }
          h=p;
        }
        cnt++;
      }
      return head;
    }
};
